import { ref, computed } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import socketManager from '@/utils/socketManager'

/**
 * 联系人Socket.IO管理组合式函数
 */
export function useContactSocket() {
  const authStore = useAuthStore()

  // 响应式状态
  const isConnected = ref(false)
  const friendsOnlineStatus = ref<Map<number, boolean>>(new Map())
  const pendingFriendRequests = ref<any[]>([])
  const friendRequestNotifications = ref<any[]>([])

  // 计算属性
  const onlineFriendsCount = computed(() => {
    return Array.from(friendsOnlineStatus.value.values()).filter(Boolean).length
  })

  const pendingRequestsCount = computed(() => {
    return pendingFriendRequests.value.length
  })

  /**
   * 初始化联系人Socket连接
   */
  const initContactSocket = async () => {
    if (!authStore.isAuthenticated) {
      console.warn('⚠️ 用户未登录，跳过联系人Socket初始化')
      return
    }

    try {
      const userId = authStore.user?.id
      if (!userId) {
        throw new Error('无法获取用户ID')
      }

      // 使用现有的socketManager连接
      if (!socketManager.isConnected) {
        await socketManager.connect(userId)
      }

      // 设置联系人相关事件监听器
      setupContactEventListeners()

      // 获取好友在线状态
      getFriendsOnlineStatus()

      isConnected.value = true
      console.log('✅ 联系人Socket初始化成功')
      
    } catch (error) {
      console.error('❌ 联系人Socket初始化失败:', error)
      ElMessage.error('联系人实时功能连接失败，请刷新页面重试')
    }
  }

  /**
   * 设置联系人相关事件监听器
   */
  const setupContactEventListeners = () => {
    // 好友状态变化
    socketManager.on('friend:status_change', (data: any) => {
      console.log('👤 好友状态变化:', data)
      handleFriendStatusChange(data)
    })

    // 收到好友申请
    socketManager.on('friend:request_received', (data: any) => {
      console.log('📨 收到好友申请:', data)
      handleFriendRequestReceived(data)
    })

    // 好友申请被接受
    socketManager.on('friend:request_accepted', (data: any) => {
      console.log('✅ 好友申请被接受:', data)
      handleFriendRequestAccepted(data)
    })

    // 好友申请被拒绝
    socketManager.on('friend:request_rejected', (data: any) => {
      console.log('❌ 好友申请被拒绝:', data)
      handleFriendRequestRejected(data)
    })

    // 好友在线状态响应
    socketManager.on('friendsOnlineStatus', (data: any) => {
      console.log('📊 好友在线状态:', data)
      updateFriendsOnlineStatus(data.friends)
    })

    // 好友房间加入成功
    socketManager.on('friendRoomJoined', (data: any) => {
      console.log('🏠 加入好友房间成功:', data)
    })

    // 错误处理
    socketManager.on('error', (data: any) => {
      console.error('❌ 联系人Socket错误:', data)
      ElMessage.error(data.message || '联系人功能发生错误')
    })
  }

  /**
   * 处理好友状态变化
   */
  const handleFriendStatusChange = (data: any) => {
    const { userId, status } = data
    const isOnline = status === 'ONLINE'
    
    friendsOnlineStatus.value.set(userId, isOnline)
    
    // 可选：显示好友上线/下线通知
    if (isOnline) {
      console.log(`🟢 好友 ${userId} 上线了`)
    } else {
      console.log(`🔴 好友 ${userId} 下线了`)
    }
  }

  /**
   * 处理收到好友申请
   */
  const handleFriendRequestReceived = (data: any) => {
    const { request } = data
    
    // 添加到待处理申请列表
    pendingFriendRequests.value.unshift(request)
    
    // 显示通知
    ElNotification({
      title: '新的好友申请',
      message: `${request.fromUser.realName || request.fromUser.username} 想要添加您为好友`,
      type: 'info',
      duration: 5000,
      onClick: () => {
        // 可以跳转到好友申请页面
        console.log('点击查看好友申请')
      }
    })

    // 添加到通知列表
    friendRequestNotifications.value.unshift({
      id: request.id,
      type: 'received',
      message: `${request.fromUser.realName || request.fromUser.username} 想要添加您为好友`,
      timestamp: new Date(),
      data: request
    })
  }

  /**
   * 处理好友申请被接受
   */
  const handleFriendRequestAccepted = (data: any) => {
    const { request } = data
    
    // 显示成功通知
    ElNotification({
      title: '好友申请已接受',
      message: `${request.toUser.realName || request.toUser.username} 接受了您的好友申请`,
      type: 'success',
      duration: 3000
    })

    // 添加到通知列表
    friendRequestNotifications.value.unshift({
      id: request.id,
      type: 'accepted',
      message: `${request.toUser.realName || request.toUser.username} 接受了您的好友申请`,
      timestamp: new Date(),
      data: request
    })

    // 更新好友在线状态
    getFriendsOnlineStatus()
  }

  /**
   * 处理好友申请被拒绝
   */
  const handleFriendRequestRejected = (data: any) => {
    const { request } = data
    
    // 显示通知
    ElNotification({
      title: '好友申请被拒绝',
      message: `${request.toUser.realName || request.toUser.username} 拒绝了您的好友申请`,
      type: 'warning',
      duration: 3000
    })

    // 添加到通知列表
    friendRequestNotifications.value.unshift({
      id: request.id,
      type: 'rejected',
      message: `${request.toUser.realName || request.toUser.username} 拒绝了您的好友申请`,
      timestamp: new Date(),
      data: request
    })
  }

  /**
   * 更新好友在线状态
   */
  const updateFriendsOnlineStatus = (friends: any[]) => {
    friends.forEach(friend => {
      friendsOnlineStatus.value.set(friend.userId, friend.isOnline)
    })
  }

  /**
   * 获取好友在线状态
   */
  const getFriendsOnlineStatus = () => {
    if (socketManager.isConnected) {
      socketManager.emit('getFriendsOnlineStatus', {})
    }
  }

  /**
   * 加入好友房间（为私聊做准备）
   */
  const joinFriendRoom = (friendId: number) => {
    if (socketManager.isConnected) {
      socketManager.emit('joinFriendRoom', { friendId })
    }
  }

  /**
   * 检查好友是否在线
   */
  const isFriendOnline = (userId: number): boolean => {
    return friendsOnlineStatus.value.get(userId) || false
  }

  /**
   * 清除通知
   */
  const clearNotifications = () => {
    friendRequestNotifications.value = []
  }

  /**
   * 移除待处理申请
   */
  const removePendingRequest = (requestId: number) => {
    const index = pendingFriendRequests.value.findIndex(req => req.id === requestId)
    if (index > -1) {
      pendingFriendRequests.value.splice(index, 1)
    }
  }

  /**
   * 断开联系人Socket连接
   */
  const disconnectContactSocket = () => {
    // 清理事件监听器
    socketManager.off('friend:status_change')
    socketManager.off('friend:request_received')
    socketManager.off('friend:request_accepted')
    socketManager.off('friend:request_rejected')
    socketManager.off('friendsOnlineStatus')
    socketManager.off('friendRoomJoined')

    // 清理状态
    isConnected.value = false
    friendsOnlineStatus.value.clear()
    pendingFriendRequests.value = []
    friendRequestNotifications.value = []

    console.log('🔌 联系人Socket连接已断开')
  }

  return {
    // 状态
    isConnected,
    friendsOnlineStatus,
    pendingFriendRequests,
    friendRequestNotifications,
    
    // 计算属性
    onlineFriendsCount,
    pendingRequestsCount,
    
    // 方法
    initContactSocket,
    disconnectContactSocket,
    getFriendsOnlineStatus,
    joinFriendRoom,
    isFriendOnline,
    clearNotifications,
    removePendingRequest
  }
}
